#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    const char *filename = "mmap_test.txt";
    const char *message = "Hello, mmap!";
    HANDLE hFile, hMapFile;
    LPVOID lpMapAddress;
    DWORD file_size, bytes_written;

    // 1. 创建并打开文件
    hFile = CreateFile(
        filename,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        printf("CreateFile failed: %d\n", GetLastError());
        return 1;
    }

    // 2. 调整文件大小
    file_size = strlen(message) + 1; // +1 包含字符串结束符 '\0'
    if (!SetFilePointer(hFile, file_size - 1, NULL, FILE_BEGIN)) {
        printf("SetFilePointer failed: %d\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }
    
    if (!SetEndOfFile(hFile)) {
        printf("SetEndOfFile failed: %d\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    // 3. 创建文件映射对象
    hMapFile = CreateFileMapping(
        hFile,
        NULL,
        PAGE_READWRITE,
        0,
        file_size,
        NULL
    );

    if (hMapFile == NULL) {
        printf("CreateFileMapping failed: %d\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    // 4. 将文件映射到进程地址空间
    lpMapAddress = MapViewOfFile(
        hMapFile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        file_size
    );

    if (lpMapAddress == NULL) {
        printf("MapViewOfFile failed: %d\n", GetLastError());
        CloseHandle(hMapFile);
        CloseHandle(hFile);
        return 1;
    }

    // 5. 写入数据到映射内存
    printf("写入数据: %s\n", message);
    strcpy((char*)lpMapAddress, message);

    // 6. 验证写入结果
    printf("读取映射内存: %s\n", (char*)lpMapAddress);

    // 7. 清理资源
    UnmapViewOfFile(lpMapAddress);
    CloseHandle(hMapFile);
    CloseHandle(hFile);

    return 0;
}